﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
//using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using trunk.ViewModels;
using System.IO;
//using System.Windows.Navigation
using System.Threading;


namespace trunk.Views
{
    /// <summary>
    /// TcpClientPage.xaml 的交互逻辑
    /// </summary>
    public partial class TcpClientPage : Page
    {

        TcpClient? client;

        CancellationTokenSource? cclts;

        public TcpClientPage()
        {
            InitializeComponent();
            this.DataContext = new TcpClientPageViewModel();
            this.Unloaded += onUnloaded;
        }

        public void onUnloaded(object sender, RoutedEventArgs e)
        {
            if (this.client != null)
            {
                this.cclts.Cancel();
                //cclts = null;
                this.client.Close();
                this.client = null;
            }
        }

        //protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        //{

        //}

        private async void startConnectBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.client != null)
                {
                    MessageBox.Show("请先停止连接");
                    return;
                }

                Int32 port = 8888;
                string server = "127.0.0.1";

                // Prefer a using declaration to ensure the instance is Disposed later.
                this.client = new TcpClient(server, port);
                addMsg($"connect to server:{server},port:{port}");

                cclts = new CancellationTokenSource();
                await Task.Run(async () =>
                {
                    
                    while (true)
                    {
                        if (cclts.Token.IsCancellationRequested)
                        {
                            //cclts.Token.ThrowIfCancellationRequested();
                            break;
                        }
                        Stream stream = client.GetStream();
                        Byte[] data = new Byte[1024];
                        var task = stream.ReadAsync(data, 0, data.Length);
                        var bytes = await task;
                        var responseData = System.Text.Encoding.UTF8.GetString(data, 0, bytes);
                        var resp = $"client Received: {responseData}";
                        //addMsg(resp);
                        this.Dispatcher.Invoke(() =>
                        {
                            addMsg(resp);
                        });                        
                    }
                }, cclts.Token);

            }
            catch (ArgumentNullException ae)
            {
                Debug.WriteLine("ArgumentNullException: {0}", ae.ToString());
            }
            catch (SocketException ae)
            {
                Debug.WriteLine("SocketException: {0}", ae.ToString());
            }
        }

        private void addMsg(string msg)
        {
            (this.DataContext as TcpClientPageViewModel).ListStr.Add(msg);
        }

        private void stopConnectBtn_Click(object sender, RoutedEventArgs e)
        {
            if (this.client != null)
            {
                //(this.DataContext as TcpClientPageViewModel).ListStr.Add($"连接停止了");
                addMsg($"连接停止了");
                this.cclts.Cancel();
                //this.cclts = null;
                this.client.Close();
                this.client = null;
            }
        }

        private async void btnSend_Click(object sender, RoutedEventArgs e)
        {
            string text = sendEditBox.Text;
            if(text =="" || text == null)
            {
                MessageBox.Show("请在左侧输入消息");
                return;
            }
            if(client == null)
            {
                MessageBox.Show("网络未连接");
                return;
            }
            // Translate the passed message into ASCII and store it as a Byte array.
            Byte[] data = System.Text.Encoding.UTF8.GetBytes(text);

            // Get a client stream for reading and writing.
            NetworkStream stream = client.GetStream();

            // Send the message to the connected TcpServer.
            stream.Write(data, 0, data.Length);

            string sentStr = $"client Sent: {text}";
            Debug.WriteLine(sentStr);
            //(this.DataContext as TcpClientPageViewModel).ListStr.Add(sentStr);
            addMsg(sentStr);

            // Explicit close is not necessary since TcpClient.Dispose() will be
            // called automatically.
            // stream.Close();
            // client.Close();
        }
    }
}
